package com.zqc.security;

import cn.hutool.core.util.StrUtil;
import com.zqc.entity.SysUser;
import com.zqc.service.SysUserService;
import com.zqc.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt拦截
 */

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    public JwtUtils jwtUtils;

    @Autowired
    public UserDetailServiceImpl userDetailService;

    @Autowired
    public SysUserService userService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取jwt
        String jwt = request.getHeader(jwtUtils.getHeader());
        // 判断jwt是否为空
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request,response);
            return ;
        }

        // 解析jwt
        Claims claims = jwtUtils.getClaimByToken(jwt);
        // 判断解析是否为空，如果jwt被更改，返回空
        if (claims == null) {
            throw new JwtException("jwt 异常");
        }
        // 判断jwt是否过期
        if (jwtUtils.isTokenExpired(claims)) {
            throw new JwtException("jwt 已过期");
        }

        String username = claims.getSubject();
        SysUser sysUser = userService.getUserByUsername(username);

        // 获取用户的权限信息
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(username, sysUser.getPassword(), userDetailService.getUserAuthorities(sysUser.getId()));

        // 设置上下文鉴权
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request,response);

    }
}
